/**
 * 表单相关 Hook
 */

import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

export interface FormState {
  loading: boolean
  visible: boolean
  isEdit: boolean
}

export function useForm<T = any>(
  defaultForm: T,
  rules?: FormRules
) {
  // 表单状态
  const state = reactive<FormState>({
    loading: false,
    visible: false,
    isEdit: false
  })

  // 表单数据
  const formData = ref<T>({ ...defaultForm })
  const formRef = ref<FormInstance>()

  // 表单规则
  const formRules = ref<FormRules>(rules || {})

  // 打开表单
  const openForm = (data?: T, isEdit = false) => {
    state.visible = true
    state.isEdit = isEdit
    
    if (data) {
      formData.value = { ...data }
    } else {
      formData.value = { ...defaultForm }
    }
  }

  // 关闭表单
  const closeForm = () => {
    state.visible = false
    formData.value = { ...defaultForm }
    formRef.value?.resetFields()
  }

  // 提交表单
  const submitForm = async (submitApi: (data: T) => Promise<void>) => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      state.loading = true
      
      await submitApi(formData.value)
      
      ElMessage.success(state.isEdit ? '更新成功' : '创建成功')
      closeForm()
      
      return true
    } catch (error) {
      if (error !== false) {
        ElMessage.error(state.isEdit ? '更新失败' : '创建失败')
        console.error('提交表单失败:', error)
      }
      return false
    } finally {
      state.loading = false
    }
  }

  // 重置表单
  const resetForm = () => {
    formRef.value?.resetFields()
    formData.value = { ...defaultForm }
  }

  // 验证表单
  const validateForm = async () => {
    if (!formRef.value) return false
    
    try {
      await formRef.value.validate()
      return true
    } catch {
      return false
    }
  }

  // 验证指定字段
  const validateField = (props: string | string[]) => {
    formRef.value?.validateField(props)
  }

  // 清除验证
  const clearValidate = (props?: string | string[]) => {
    formRef.value?.clearValidate(props)
  }

  // 计算属性
  const isEdit = computed(() => state.isEdit)
  const isCreate = computed(() => !state.isEdit)
  const formTitle = computed(() => state.isEdit ? '编辑' : '新增')

  return {
    // 状态
    state,
    formData,
    formRef,
    formRules,
    
    // 计算属性
    isEdit,
    isCreate,
    formTitle,
    
    // 方法
    openForm,
    closeForm,
    submitForm,
    resetForm,
    validateForm,
    validateField,
    clearValidate
  }
}
